/**
 *
 */
package org.insia.smartposse.manager;

import org.hibernate.HibernateException;
import org.insia.smartposse.form.BooksForm;
import org.insia.smartposse.manager.iface.IManager;
import org.insia.smartposse.mapping.FreelanceBooks;
import org.insia.smartposse.mapping.dao.FreelanceBooksDAO;

/**
 * @author cmougel
 *
 */
public class FreelanceBookManager implements IManager {

	private final FreelanceBooksDAO _dao = new FreelanceBooksDAO();
	private FreelanceBooks _book;
	
	public FreelanceBookManager(){
		_book = new FreelanceBooks();
	}
	
	public FreelanceBookManager(FreelanceBooks fBook){
		_book = fBook;
	}

	public FreelanceBookManager(int id) {
		_book = _dao.get(id, _dao.getSession());
	}
	
	public int getId() {
		return _book.getId();
	}

	public void setId(int id) {
		_book.setId(id);
	}

	/**
	 * @return the URL
	 */
	public String getUrl(){
		return _book.getUrl();
	}

	/**
	 * Define the URL
	 *
	 * @param url
	 */
	public void setURL(String url){
		_book.setUrl(url);
	}

	/**
	 *
	 * @return the comment of this Book
	 */
	public String getComment(){
		return _book.getComment();
	}

	/**
	 * Define the comment
	 *
	 * @param comment
	 */
	public void setComment(String comment){
		_book.setComment(comment);
	}

	/**
	 * Define the User of this Book
	 *
	 * @param u
	 */
	public void setFreelance(UserManager freelance){
		if (freelance.isFreelance()){
			_book.setFreelance(freelance.getUser());
		} else {
			throw new HibernateException("this user is not Freelance and can't had a Book");
		}
	}

	/**
	 * @return the User manager of This Book
	 */
	public UserManager getFreelance(){
		if (null == _book.getFreelance()) {
			return new UserManager();
		} else {
			return new UserManager(_book.getFreelance());
		}
	}
	

	/* (non-Javadoc)
	 * @see org.insia.smartposse.manager.iface.IManager#save()
	 */
	public void save() {

		// No value NULL in database
		if (null == _book.getComment()){
			_book.setComment("");
		}

		if (null == _book.getUrl()){
			_book.setUrl("");
		}
		_dao.saveOrUpdate(_book);

	}
	
	public void delete() {
		_dao.delete(_book);
	}
	
	public void populateBooksForm(UserManager user, BooksForm form) {
		setFreelance(user);
		setURL(form.getUrl());
		setComment(form.getComment());
	}

}
